package com.msh.automatic.android.control.script

import android.accessibilityservice.AccessibilityService
import android.content.ComponentName
import android.content.Context
import android.os.Bundle
import android.provider.Settings
import android.text.TextUtils
import android.util.Log
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.alibaba.fastjson2.JSON
import com.msh.automatic.android.control.script.service.ScriptAccessibilityService
import com.msh.automatic.android.control.script.task.TaskManager
import com.msh.automatic.android.control.script.ui.theme.ScriptTheme
import com.msh.automatic.android.control.script.util.TaskUtil
import kotlin.system.exitProcess

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            ScriptTheme {
                Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
                    Greeting(
                        name = "Android",
                        modifier = Modifier.padding(innerPadding)
                    )
                }
            }
        }

        if(!isAccessibilityServiceEnabled(this,ScriptAccessibilityService::class.java)){
            TaskUtil.callBackActivity(null,"未打开无障碍服务",this,)
            exitProcess(0)
            return;
        }
        // 获取 Intent 中的参数
        val task = intent.getStringExtra("task")
        if(task.isNullOrBlank()){
            TaskUtil.callBackActivity(null,"task is null",this,)
            exitProcess(0)
            return;
        }
//        ScriptAccessibilityService.aiAccessibilityService.task = JSON.parseObject(task)
        Log.i("TASK","task: ${task}")
//        ScriptAccessibilityService.aiAccessibilityService.taskParams = JSON.parseObject(ScriptAccessibilityService.aiAccessibilityService.task.getString("params"))
        val taskLog = intent.getStringExtra("taskLog")  // 带默认值
        if(taskLog.isNullOrBlank()){
            TaskUtil.callBackActivity(null,"taskLog is null",this,)
            exitProcess(0)
            return
        }
        Log.i("TASK","taskLog: ${taskLog}")
//        ScriptAccessibilityService.aiAccessibilityService.taskLog = JSON.parseObject(taskLog)
        val token = intent.getStringExtra("token")  // 带默认值
        if(token.isNullOrBlank()){
            TaskUtil.callBackActivity(null,"token is null",this,)
            exitProcess(0)
            return;
        }
//        ScriptAccessibilityService.aiAccessibilityService.token = token   service.rootInActiveWindow   service.currentRootNode
        Log.i("TASK","token: ${token}")
        TaskManager.startTask(
            JSON.parseObject(task),
            JSON.parseObject(taskLog),
            token,
        )
    }
    override fun onStop() {
        super.onStop()
        this.finish()
    }

    override fun onResume() {
        super.onResume()
//        test()
    }

//    fun test(){
//        if(!isAccessibilityServiceEnabled(this, ScriptAccessibilityService::class.java)){
//            Toast.makeText(this,"未打开无障碍服务", Toast.LENGTH_LONG).show()
//            return;
//        }
//        val task = "{\"accessibilityServiceClass\":\"com.msh.automatic.android.control.script.service.ScriptAccessibilityService\",\"accessibilityServiceName\":\"美数合脚本智能服务\",\"activityClass\":\"com.msh.automatic.android.control.script.MainActivity\",\"downloadUrl\":\"https://aliyun-oss.meishuhe.cn/test/automatic-android-control-script.apk\",\"id\":\"check_vpn_status\",\"packageName\":\"com.msh.automatic.android.control.script\",\"params\":\"{}\",\"title\":\"检查vpn状态\",\"type\":\"app\",\"versionCode\":1}"
//        val taskLog = "{\"deviceId\":\"e9d0d4708f99d770\",\"id\":\"019753fb-de52-723a-8812-0b865a1a6747\",\"message\":\"\",\"status\":\"execute\",\"taskId\":\"check_vpn_status\"}"
//        val token = "eyJraWQiOiJtc2giLCJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJtc2giLCJzdWIiOiJlOWQwZDQ3MDhmOTlkNzcwIiwiYXVkIjoibXNoIiwiZXhwIjoxNzUxODgxNDc0LCJpYXQiOjE3NDkyODk0NzR9.Atixhb3MY5qC5l-pI9NsIZjh3tMZdX6PHKRRYzaUlpSx4hx7DlKYW8UnmiBZxHQI4jjJVuOzKs5bJB5WhDFDzlbPcrrOIFVLTPbUYIq-DKadVmfoSYZ1Rsr7nzpqM22SZQIi_BEDnUShEAG_NOJmNZ1cQbcLiIehWzCjA1fUxmNZAeSNKob2hJoJ5mZ-D9alcONt8g-JuqGz9GZSO2acGTxRUi3JtF-kOkuX2QxJJo_fkONwKY7uuzy5QDmUktozsyfW5dtfGqCRDjeIthjlGAbXphsviRmxDv7OWyzyomzGxnpcnYEiQkzT6bMlwODXIvmZiBqeo1TGD7NTtWlymg"
//        TaskManager.startTask(
//            JSON.parseObject(task),
//            JSON.parseObject(taskLog),
//            token,
//        )
//    }
}

/**
 * 判断无障碍服务是否启用
 */
fun isAccessibilityServiceEnabled(context: Context, serviceClass: Class<out AccessibilityService>): Boolean {
    val expectedComponentName = ComponentName(context, serviceClass)
    val enabledServices = Settings.Secure.getString(
        context.contentResolver,
        Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES
    ) ?: return false

    val colonSplitter = TextUtils.SimpleStringSplitter(':')
    colonSplitter.setString(enabledServices)
    for (component in colonSplitter) {
        if (ComponentName.unflattenFromString(component) == expectedComponentName) {
            return true
        }
    }
    return false
}
@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
    Text(
        text = "Hello $name!",
        modifier = modifier
    )
}

@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
    ScriptTheme {
        Greeting("Android")
    }
}